#!/usr/bin/bash
#
#  Usage: 下载并更新GeoIP数据库
#  Issue: 2024-05-17
# Author: Leon Hsia
#   Mail: waxwork3@163.com
#
base_path=$(dirname $(realpath $0))
cd $base_path/nginx

# download GeoLite2-Country.tar.gz
url='https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country&license_key=your_license_key&suffix=tar.gz'
file=$(echo $url \
|grep -oP '(?<=edition_id=)[^&]*|(?<=suffix=)[^&]*' \
|tr -d '\n' |sed 's/Countrytar/Country.tar/')
echo "try to download '${file}'."
file_size_local=`\ls -l GeoLite2-Country.tar.gz 2>/dev/null |grep GeoLite2-Country.tar.gz |cut -d ' ' -f5`
file_size_remote=`curl -I $url 2>/dev/null |grep length |cut -d ' ' -f2 |tr -d '\r'`
# download only if remote file change.
if test "$file_size_local" != "$file_size_remote";
then
    wget --verbose -O $file $url >/dev/null 2>&1
fi
test -e $file || exit

# download GeoLite2-Country.tar.gz.sha256
url='https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country&license_key=your_license_key&suffix=tar.gz.sha256'
file=$(echo $url \
|grep -oP '(?<=edition_id=)[^&]*|(?<=suffix=)[^&]*' \
|tr -d '\n' |sed 's/Countrytar/Country.tar/')
echo "try to download '${file}'."
\rm $file 2>/dev/null
wget --verbose -O $file $url >/dev/null 2>&1
test -e $file || exit

# validate download
sed -i 's/Country[^.]*/Country/' $file
\rm ${file%%.sha256}.ok >/dev/null 2>&1
echo "validate download '${file}'."
sha256sum -c $file >/dev/null 2>&1 && touch ${file%%.sha256}.ok

# extract file
echo "extract file '${file%%.sha256}'."
test -e ${file%%.sha256}.ok || exit
tar -zxvf ${file%%.sha256} >/dev/null 2>&1 #&& \rm GeoLite2-Country.tar.gz{,.ok,.sha256}
mmdb=$(find . -mindepth 2 -name GeoLite2-Country.mmdb |sort -r |head -1)
test -z $mmdb && exit
\mv $mmdb ./ && \rm GeoLite2-Country.tar.gz.ok GeoLite2-Country.tar.gz.sha256